import psycopg2
import requests
from tqdm import tqdm
from urllib3.exceptions import InsecureRequestWarning
from urllib3 import disable_warnings

disable_warnings(InsecureRequestWarning)  # 禁用不安全请求警告

# 连接到 PostgreSQL 数据库
conn = psycopg2.connect(
    dbname="x-easy-digital-twins-prod",
    user="digital_3d",
    password="xtc#2023@3d",
    host="10.11.2.97",
    port="4101",
)

projectId = "1729042150414426113"


# 获取模型的url数据
def getModelUrlData(projectId: str):
    # 创建一个游标对象，用于执行 SQL 语句
    cur = conn.cursor()

    # 执行 SQL 查询
    cur.execute(f"SELECT * FROM dt_scenes where project_id='{projectId}'")

    # 获取查询结果
    rows = cur.fetchall()

    modelsData = []

    # 打印查询结果
    for row in rows:
        sceneData = conn.cursor()
        sceneData.execute(f"SELECT * FROM dt_scene_data where scene_mark='{row[0]}'")
        dataSet = sceneData.fetchall()
        sceneData.close()
        for data in dataSet:
            modelsData.append(data[7])

    # 关闭游标对象
    cur.close()

    # 关闭数据库连接
    conn.close()

    return set(modelsData)


# 下载模型数据到本地
def downModel(modelUrl: str):
    url = f"https://10.11.1.130:5082/three-d/{modelUrl}"
    response = requests.get(url, verify=False)

    if response.status_code == 200:
        with open(f"models/{modelUrl}", "wb") as file:
            file.write(response.content)


# 根据项目下载文件
modelsData = getModelUrlData("1729042150414426113")
for modelUrl in tqdm(modelsData):
    downModel(modelUrl)
